<?php

// +--------------------------------------------
// | Name: 星空后台 系统配置验证规则
// +--------------------------------------------
// | Version: V5.0
// +--------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +--------------------------------------------
// | Time: 2021-04-08 11:26
// +--------------------------------------------
declare(strict_types=1);

namespace app\common\validate;

use  app\common\model\Config as ConfigModel;
use think\Validate;

/**
 * @xk 系统配置验证规则
 */
class Config extends Validate
{
    protected $rule = [
      'config_id' => 'number|min:1',
      'name' => 'require|min:2|max:100',
      'sign' => 'require|min:2|max:100|checkSign',
      'sign' => 'checkSign',
      'site_id' => 'number|between:1,20', //最大允许20个站点
      'type_id' => 'number|between:1,10',
      'status' => 'in:0,1',
    ];

    protected $message = [
      'name.require' => '请输入变量名称',
      'sign.require' => '请输入变量标志',
      'sign.checkSign' => '当前标志已经存在请更换',
      'site_id' => '请选择所属配置',
      'type_id' => '请选择变量类型',
      'status' => '是否显示不符合条件',
    ];

    protected $scene = [
      'create' => ['name', 'sign', 'site_id', 'type_id', 'status'],
      'edit' => ['config_id', 'name', 'sign', 'site_id', 'type_id', 'status'],
      'name' => ['name'],
      'sign' => ['sign']
    ];

    /**
     * @xk 自定义验证规则
     *
     * 验证 变量标志是否存在重复
     *
     * @method checkSign
     *
     * @param [type] $value [description]
     * @param [type] $data  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-16T13:12:28+080
     */
    protected function checkSign($value)
    {
        $configModel = new ConfigModel();
        $param = request()->param();
        $act = isset($param['act'])?$param['act']:'sign';
        $condition = [];
        $condition[] = ['sign', '=', $value];
        switch ($act) {
            case 'create':
              $count = $configModel->where($condition)->count();
              if ($count > 0) {
                  return false;
              }

              return true;
              break;
            case 'sign':
              $count = $configModel->where($condition)->count();
              if ($count > 0) {
                  return false;
              }

              return true;
              break;
            case 'edit':
              $config_id = $configModel->where($condition)->value('config_id');
              if($config_id <= 0){
                  return true;
              }
              if ($config_id == $param['config_id']) {
                  return true;
              }

              return false;
              break;
        }
    }
}
